package com.lwd.spring.study.core.BeanFactoryPostProcessor;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionVisitor;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringValueResolver;

import java.util.List;
import java.util.Set;

@Component("bfpp")
public class ObscenityRemovingBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    private List<String> obscenity;

    {
        obscenity =  Lists.newArrayList("lwd", "2", "3", "4","simpleBean");
    }


    public ObscenityRemovingBeanFactoryPostProcessor(List<String> obscenity) {
        this.obscenity = obscenity;
    }

    public ObscenityRemovingBeanFactoryPostProcessor() {
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
        System.out.println("beanDefinitionNames = " + JSON.toJSONString(beanDefinitionNames));
        for (String beanDefinitionName : beanDefinitionNames) {
            BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanDefinitionName);
            // 创建了一个string类型的解析器
            StringValueResolver stringValueResolver = new StringValueResolver() {
                @Override
                public String resolveStringValue(String strVal) {
                    if (isObscene(strVal)) {
                        return "*****";
                    }
                    return strVal;
                }
            };
            // 构建beanDefinition解析器
            BeanDefinitionVisitor beanDefinitionVisitor = new BeanDefinitionVisitor(stringValueResolver);
            // 使用beanDefinition解析器
            beanDefinitionVisitor.visitBeanDefinition(beanDefinition);
        }

    }

    private boolean isObscene(String strVal) {
        String s = strVal.toString().toUpperCase();
        System.out.println("strVal = " + strVal);
        return obscenity.contains(s);
    }
}